package cm.zhentao.service.impl;

import cm.zhentao.pojo.dto.LoginDto;
import cm.zhentao.utils.AppJwtUtil;
import cm.zhentao.entity.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cm.zhentao.pojo.User;
import cm.zhentao.service.UserService;
import cm.zhentao.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author Lenovo
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-07-17 10:50:47
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 登录
     * @param loginDto
     * @return
     */
    @Override
    public Result login(LoginDto loginDto) {
        if (StringUtils.isBlank(loginDto.getUsername())||StringUtils.isBlank(loginDto.getPassword())){
            return Result.ERROR("账号或密码为空");
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, loginDto.getUsername());
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (user==null){
            return Result.ERROR("该用户不存在");
        }
        if (loginDto.getPassword().equals(user.getPassword())){
            String token = AppJwtUtil.getToken(user.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            //将用户信息存入redis中
            redisTemplate.opsForValue().set("user",user);
            map.put("token",token);
            map.put("user",user);
            return Result.OK(map);
        }else {
            return Result.ERROR("密码错误");
        }
    }
}




